package com.glorysoft.wangnianxinpda.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glorysoft.wangnianxinpda.R;
import com.glorysoft.wangnianxinpda.adapter.MaterialExchangeAdapter;
import com.glorysoft.wangnianxinpda.adapter.MaterialExchangeInfoAdapter;
import com.glorysoft.wangnianxinpda.base.BaseActivity;
import com.glorysoft.wangnianxinpda.base.Constant;
import com.glorysoft.wangnianxinpda.entity.MaterialInfoEntity;
import com.glorysoft.wangnianxinpda.entity.PDACurrentMtReturnEntity;
import com.glorysoft.wangnianxinpda.entity.net.ResponseEntity;
import com.glorysoft.wangnianxinpda.utils.GsonUtils;
import com.glorysoft.wangnianxinpda.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_CommonCallback;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MaterialExchangeActivity extends BaseActivity {
    private Context mContext;

    private LinearLayout llMain;

    private TextView tv_current_eqp_no;//当前设备

    private RecyclerView rv_data_out;//物料信息

    private Button btn_on_mat;//上料

    private PDACurrentMtReturnEntity mCurrentMtReturnEntity;//设备物料信息
    private List<MaterialInfoEntity> mMaterialDetailInfoList = new ArrayList<>();//物料信息

    private String sEqpID;//设备号
    private String sProcess;//当前工序

    private MaterialExchangeAdapter mAdapter;//物料信息适配器

    private FreeUI_GeneralFragmentDialog mMessageDialog;//消息提示框

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_material_exchange;
    }

    @Override
    protected void initView() {
        mContext = this;

        llMain = findViewById(R.id.llMain);

        tv_current_eqp_no = findViewById(R.id.tv_current_eqp_no);

        rv_data_out = findViewById(R.id.rv_data_out);
        btn_on_mat = findViewById(R.id.btn_on_mat);

        btn_on_mat.setOnClickListener(v -> {
            Intent intent = new Intent(getBaseContext(), MaterialOnScanActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("EQPID", sEqpID);
            intent.putExtra("showPlugin", "header");
            startActivity(intent);
        });

    }

    @Override
    protected void initData() {
        Bundle extras = getIntent().getExtras();
        sEqpID = extras.getString("EQPID");
        sProcess = extras.getString("Process");
        tv_current_eqp_no.setText(sEqpID);

        //初始化列表、适配器
        mAdapter = new MaterialExchangeAdapter(R.layout.adapter_material_exchange, mMaterialDetailInfoList);
        rv_data_out.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        mAdapter.setListener(new MaterialExchangeInfoAdapter.OnClickListener() {
            @Override
            public void off(MaterialInfoEntity.MaterialDescEntity item,String code) {
                showMessageDialog(String.format(getResources().getString(R.string.is_confirm_disembark), item.getMATERIALSPECS()), item,code);
            }

            @Override
            public void exchange(MaterialInfoEntity.MaterialDescEntity item,String code) {
                Intent intent = new Intent(getBaseContext(), MaterialExchangeScanActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.putExtra("EQPID", sEqpID);
                intent.putExtra("showPlugin", "header");
//                intent.putExtra("MaterialInfo", item);
                intent.putExtra("MATERIALCODE", code);
                intent.putExtra("MATERIALTYPE", item.getMATERIALTYPE());
                intent.putExtra("MATLOT", item.getMATLOT());
                intent.putExtra("USERQTY", item.getUSEQTY());
                startActivity(intent);
            }
        });
        rv_data_out.setAdapter(mAdapter);

        //region 测试

//        String sJson = "{\n" +
//                "\t\"HEADER\": {\n" +
//                "\t\t\"TRANSACTIONID\": \"EDA123446-6CF1-5B29-860B-631D32W91A18\",\n" +
//                "\t\t\"MESSAGENAME\": \"PDACurrentMtResponse\",\n" +
//                "\t\t\"EVENTUSER\": \"EAP\",\n" +
//                "\t\t\"EVENTTIME\": \"2021-03-25 16:28:59.585\"\n" +
//                "\t},\n" +
//                "\t\"BODY\": {\n" +
//                "\t\t\"WORK_NO\": \"007\",\n" +
//                "\t\t\"EQPID\": \"WB001\",\n" +
//                "\t\t\"Process\": \"WB\",\n" +
//                "\t\t\"Materials\": [\n" +
//                "\t\t\t{\n" +
//                "\t\t\t\t\"MATERIAL_ID\": \"11\",\n" +
//                "\t\t\t\t\"MAT_NO\": \"11\",\n" +
//                "\t\t\t\t\"MATERIAL_NAME\": \"11\",\n" +
//                "\t\t\t\t\"SPECS\": \"11\",\n" +
//                "\t\t\t\t\"MATERIAL_TYPE\": \"11\"\n" +
//                "\t\t\t},\t\t{\n" +
//                "\t\t\t\t\"MATERIAL_ID\": \"22\",\n" +
//                "\t\t\t\t\"MAT_NO\": \"22\",\n" +
//                "\t\t\t\t\"MATERIAL_NAME\": \"22\",\n" +
//                "\t\t\t\t\"SPECS\": \"22\",\n" +
//                "\t\t\t\t\"MATERIAL_TYPE\": \"22\"\n" +
//                "\t\t\t},\t\t{\n" +
//                "\t\t\t\t\"MATERIAL_ID\": \"33\",\n" +
//                "\t\t\t\t\"MAT_NO\": \"33\",\n" +
//                "\t\t\t\t\"MATERIAL_NAME\": \"33\",\n" +
//                "\t\t\t\t\"SPECS\": \"33\",\n" +
//                "\t\t\t\t\"MATERIAL_TYPE\": \"33\"\n" +
//                "\t\t\t}\n" +
//                "\t\t]\n" +
//                "\n" +
//                "\t},\n" +
//                "\t\"RETURN\": {\n" +
//                "\t\t\"RETURNCODE\": \"0\",\n" +
//                "\t\t\"RETURNMESSAGE\": \"信息获取成功\"\n" +
//                "\t}\n" +
//                "}";
//
//        try {
//            JSONObject jsonObject = new JSONObject(sJson);
//            String body = jsonObject.getString("BODY");
//            mCurrentMtReturnEntity = GsonUtils.getObject(body, PDACurrentMtReturnEntity.class);
//
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        if (mMaterialDetailInfoList != null){
//            mMaterialDetailInfoList.clear();
//        }
//        mMaterialDetailInfoList.addAll(mCurrentMtReturnEntity.getMaterials());
//        mAdapter.setNewData(mMaterialDetailInfoList);
        //endregion

    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle(getString(R.string.materialReplacement));
        return new FreeUI_AddViewEntity(getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY), llMain);
    }

    //region 接口调用

    //获取设备物料信息
    private void getEqpMaterialInfo() {
        FreeUI_EntityCallBack<ResponseEntity<PDACurrentMtReturnEntity>> callBack = new FreeUI_DialogEntityCallBack<ResponseEntity<PDACurrentMtReturnEntity>>(new TypeToken<ResponseEntity<PDACurrentMtReturnEntity>>() {
        }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseEntity<PDACurrentMtReturnEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(true, getSupportFragmentManager())) {
                    showToast(response.body().getMsg(), true);
                    mCurrentMtReturnEntity = response.body().getData();
                    if (mMaterialDetailInfoList != null) {
                        mMaterialDetailInfoList.clear();
                    }
                    mMaterialDetailInfoList.addAll(mCurrentMtReturnEntity.getMaterials());
                    mAdapter.setNewData(mMaterialDetailInfoList);
                }
            }

            @Override
            public void onError(Response<ResponseEntity<PDACurrentMtReturnEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "PDACurrentMt");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("WORK_NO", Constant.loginEntity.getWORK_NO());//工号
        map.addProperty("EQPID", sEqpID);//设备号
//        map.addProperty("Process", sProcess);//工序
        String method = "PDACurrentMt";
        NetUtils.requestPostNet("PDACurrentMtRequest", method, this, map, callBack);
    }

    //下机
    private void offEAPMat(MaterialInfoEntity.MaterialDescEntity entity,String code) {
        if (entity == null) {
            return;
        }

        FreeUI_EntityCallBack<ResponseEntity<?>> callBack = new FreeUI_DialogEntityCallBack<ResponseEntity<?>>(new TypeToken<ResponseEntity<?>>() {
        }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseEntity<?>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(false, getSupportFragmentManager())) {
                    mCurrentMtReturnEntity.getMaterials().remove(entity);
                    mMaterialDetailInfoList.remove(entity);
                    mAdapter.setNewData(mMaterialDetailInfoList);
                    showToast(response.body().getMsg(), true);
                }
            }

            @Override
            public void onError(Response<ResponseEntity<?>> response) {
                super.onError(response);
                loadError(response.getException(), "PDAOFFEQPMat");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("WORK_NO", Constant.loginEntity.getWORK_NO());//员工编号
        map.addProperty("EQPID", sEqpID);//设备编号
        map.addProperty("MATERIALID", code);//实物编号
        map.addProperty("MATERIALTYPE", entity.getMATERIALTYPE());//实物类型
        map.addProperty("MATLOT", entity.getMATLOT());//实物类型
        map.addProperty("USERQTY", entity.getUSEQTY());//实物类型
        String method = "PDAOFFEQPMat";
        NetUtils.requestPostNet("PDAOFFEQPMatRequest", method, this, map, callBack);
    }

    //endregion

    //消息提示框
    private void showMessageDialog(String message, MaterialInfoEntity.MaterialDescEntity entity,String code) {
        mMessageDialog = new FreeUI_GeneralFragmentDialog();
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_prompt2, null);
        Button btnConfirm = view.findViewById(R.id.btnConfirm);
        Button btnCancel = view.findViewById(R.id.btnCancel);
        TextView tvTips = view.findViewById(R.id.tvTips);
        btnConfirm.setOnClickListener(v -> {
            mMessageDialog.dismiss();
            offEAPMat(entity,code);//物料下机
        });
        btnCancel.setOnClickListener(v -> mMessageDialog.dismiss());
        tvTips.setText(message);
        mMessageDialog.setLayout(view);
//        mMessageDialog.getDialog().setCanceledOnTouchOutside(false);
        mMessageDialog.show(getSupportFragmentManager(), "isDelete");
        mMessageDialog.setCallBack(() -> mMessageDialog = null);

    }

    @Override
    protected void onStart() {
        super.onStart();
        getEqpMaterialInfo();//获取设备物料信息
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //region 测试
//        if (resultCode == -2 && requestCode == 105){
//            Bundle extras = data.getExtras();
//            MaterialInfoEntity entity = new MaterialInfoEntity();
//            entity = (MaterialInfoEntity) extras.getSerializable("materialInfo");
//            //更换物料
//            if (entity != null){
//                mMaterialDetailInfoList.get(nPosition).setMAT_NO(entity.getMAT_NO());
//                mMaterialDetailInfoList.get(nPosition).setMATERIAL_ID(entity.getMATERIAL_ID());
//                mMaterialDetailInfoList.get(nPosition).setMATERIAL_NAME(entity.getMATERIAL_NAME());
//                mMaterialDetailInfoList.get(nPosition).setMATERIAL_TYPE(entity.getMATERIAL_TYPE());
//                mMaterialDetailInfoList.get(nPosition).setSPECS(entity.getSPECS());
//                mCurrentMtReturnEntity.setMaterials(mMaterialDetailInfoList);
//                mAdapter.setData(nPosition, entity);
//            }
//        }
        //endregion
    }
}